package com.jone.bang.service;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.jone.bang.model.WordItem;

public class FileManager {
	
	public static final String fullpath = "/data/data/com.jone.bang/";
	
	private static final String TAG = "FileManager";
  
	/**
	 * write content to fullpath
	 * @param content
	 * @param fullPath
	 */
	public static void writeToFile(String content, String filename) {
		try {
			FileOutputStream out = new FileOutputStream(fullpath+filename,false) ;
	        StringBuffer sb = new StringBuffer() ;
	        sb.append(content) ;
	        out.write(sb.toString().getBytes("gbk")) ;
	        out.flush() ;
	        out.close() ;
		} catch (IOException e) {
			Log.e(TAG, "write file error:"+e.toString());
		}
	}
	
	public static void saveHtml(String content) throws IOException {
		FileOutputStream out = null;		
		out = new FileOutputStream("/sdcard/temp_html.html",false) ;
        StringBuffer sb = new StringBuffer() ;
        sb.append(content) ;
        out.write(sb.toString().getBytes("UTF-8")) ;
        out.flush() ;
        out.close();		
	}

	/**
	 * read file
	 * @param path
	 * @return
	 */
	public static String readFile(String fileName) {
		File file = new File(fullpath+fileName);
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			//以行为单位读取文件内容，一次读一整行
			reader = new BufferedReader(new InputStreamReader (new FileInputStream(file),"gbk"));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {				
				sb.append(tempString).append("\n");
				line++;
			}
			reader.close();
		} catch (IOException e) {
			Log.e(TAG, "read file error:"+e.toString());
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb.toString();
	}

	/**
	 * string to list
	 * @param content
	 * @return
	 */
	public static List<WordItem> stringToList(String content) {
		if (content == null || "".equals(content))
			return null;
		
		List<WordItem> list = new ArrayList<WordItem>();		
		String[] line = content.split("\n");
		for(int i=0;i<line.length;i++){
			if(!"".equals(line[i])){	
				WordItem item = new WordItem();	
				item.setName(line[i]);
				list.add(item);
			}
		}
		return list;
	}
	
	public static List<WordItem> readFileToList(String fileName){
		return stringToList(readFile(fileName));
	}

}